package lwk.juc.collection;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author:lwk
 * @create: 2022-08-12 22:04
 * @Description: List集合测试
 *
 * Map<String, String> map = new HashMap<>();<br>
 * 多个线程操作线程不安全的集合时（HashMap）,会发生并发修改异常.<br>
 * java.util.ConcurrentModificationException:并发修改异常.<br><br>
 * 解决方案：<br>
 * <pre>
 * 1、Map<String, String> map = new Hashtable<>();<br>
 * 2、Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
 * synchronizedMap就是在map的操作外包加了一层synchronize同步控制,
 * 注意使用Iterator遍历时,异步修改map的结构,同样也会发生并法修改异常.<br>
 * 3、Map<String, String> map = new ConcurrentHashMap<>();
 * CAS + synchronized
 * 参考：阿里面试题：ConcurrentHashMap为什么是线程安全的？
 * @see <a href="https://blog.csdn.net/zycxnanwang/article/details/105424734">阿里面试题：ConcurrentHashMap为什么是线程安全的？</a>
 * </pre>
 */

public class MapTest {
    public static void main(String[] args) throws InterruptedException {

        //Map<String, String> map = new Hashtable<>();
        //Map<String, String> map = new HashMap<>();
        //Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
        Map<String, String> map = new ConcurrentHashMap<>();
        for (int i = 1; i <= 100; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,5));
                System.out.println(map);
            }).start();
        }
        Thread.sleep(100);
        new Thread(()-> {
            Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }
        }).start();
        new Thread(()->{
            map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,5));
            System.out.println(map);
        }).start();
    }
}
